D:\a\cssh-rs\cssh-rs\cssh-rs-core\src\client\pty.rs
Line | Count | Source |
1 | | //! ConPTY that runs `ssh` and answers its startup cursor-position query. |
2 | | |
3 | | use std::io::{self, Read, Write}; |
4 | | use std::sync::{Arc, Mutex, PoisonError}; |
5 | | |
6 | | use log::error; |
7 | | use portable_pty::{native_pty_system, Child, CommandBuilder, MasterPty, PtySize}; |
8 | | |
9 | | use crate::utils::windows::WindowsApi; |
10 | | |
11 | | /// Device Status Report query conhost sends at startup, blocking until answered. |
12 | | const DSR_QUERY: &[u8] = b"\x1b[6n"; |
13 | | /// Cursor position report answering [`DSR_QUERY`]: row 1, column 1. |
14 | | const DSR_REPLY: &[u8] = b"\x1b[1;1R"; |
15 | | |
16 | | /// PTY master writer shared by every input source. |
17 | | pub(crate) type SharedWriter = Arc<Mutex<Box<dyn Write + Send>>>; |
18 | | |
19 | | /// A spawned SSH child and the PTY master it runs on. |
20 | | pub(crate) struct ClientPty { |
21 | | pub(crate) writer: SharedWriter, |
22 | | pub(crate) reader: Box<dyn Read + Send>, |
23 | | pub(crate) child: Box<dyn Child + Send + Sync>, |
24 | | pub(crate) child_pid: u32, |
25 | | /// Keeps the pseudoconsole open. |
26 | | pub(crate) master: Box<dyn MasterPty + Send>, |
27 | | } |
28 | | |
29 | | /// Run `program` with `arguments` on a new PTY. |
30 | | /// |
31 | | /// # Arguments |
32 | | /// |
33 | | /// * `program` - The SSH program to run. |
34 | | /// * `arguments` - Arguments passed to `program`. |
35 | | /// * `size` - Initial PTY size. |
36 | | /// |
37 | | /// # Returns |
38 | | /// |
39 | | /// The spawned [`ClientPty`], or the error that prevented spawning it. |
40 | | #[cfg_attr(coverage_nightly, coverage(off))] |
41 | | pub(crate) fn spawn_client_pty( |
42 | | program: &str, |
43 | | arguments: &[String], |
44 | | size: PtySize, |
45 | | ) -> io::Result<ClientPty> { |
46 | | let pair = native_pty_system() |
47 | | .openpty(size) |
48 | | .map_err(|err| return io::Error::other(err.to_string()))?; |
49 | | |
50 | | let mut command = CommandBuilder::new(program); |
51 | | command.args(arguments); |
52 | | let child = pair |
53 | | .slave |
54 | | .spawn_command(command) |
55 | | .map_err(|err| return io::Error::other(err.to_string()))?; |
56 | | // Process group 0 would signal every process on this console. |
57 | | let child_pid = child |
58 | | .process_id() |
59 | | .ok_or_else(|| return io::Error::other("spawned PTY child has no process id"))?; |
60 | | // Otherwise reading the master never sees EOF once the child exits. |
61 | | drop(pair.slave); |
62 | | |
63 | | let writer = pair |
64 | | .master |
65 | | .take_writer() |
66 | | .map_err(|err| return io::Error::other(err.to_string()))?; |
67 | | let reader = pair |
68 | | .master |
69 | | .try_clone_reader() |
70 | | .map_err(|err| return io::Error::other(err.to_string()))?; |
71 | | |
72 | | return Ok(ClientPty { |
73 | | writer: Arc::new(Mutex::new(writer)), |
74 | | reader, |
75 | | child, |
76 | | child_pid, |
77 | | master: pair.master, |
78 | | }); |
79 | | } |
80 | | |
81 | | /// Return the size of the visible console window. |
82 | | /// |
83 | | /// # Arguments |
84 | | /// |
85 | | /// * `api` - The Windows API implementation to use. |
86 | | /// |
87 | | /// # Returns |
88 | | /// |
89 | | /// The size, or `None` if the console cannot be queried. |
90 | 1 | pub(crate) fn console_viewport_size(api: &dyn WindowsApi) -> Option<PtySize> { |
91 | 1 | let window = api.get_console_screen_buffer_info_ex().ok()?0 .srWindow; |
92 | 1 | return Some(PtySize { |
93 | 1 | rows: (window.Bottom - window.Top + 1) as u16, |
94 | 1 | cols: (window.Right - window.Left + 1) as u16, |
95 | 1 | ..PtySize::default() |
96 | 1 | }); |
97 | 1 | } |
98 | | |
99 | | /// Answer and strip every [`DSR_QUERY`] in the PTY output. |
100 | | /// |
101 | | /// # Arguments |
102 | | /// |
103 | | /// * `chunk` - Bytes newly read from the PTY master. |
104 | | /// * `carry` - A query prefix held back from the previous chunk; updated here. |
105 | | /// * `master` - PTY master writer the reply is sent to. |
106 | | /// |
107 | | /// # Returns |
108 | | /// |
109 | | /// The bytes to render. |
110 | 5 | pub(crate) fn scan_and_answer_dsr( |
111 | 5 | chunk: &[u8], |
112 | 5 | carry: &mut Vec<u8>, |
113 | 5 | master: &Mutex<impl Write>, |
114 | 5 | ) -> Vec<u8> { |
115 | 5 | let mut buffer = std::mem::take(carry); |
116 | 5 | buffer.extend_from_slice(chunk); |
117 | | |
118 | 5 | let mut rendered = Vec::with_capacity(buffer.len()); |
119 | 5 | let mut position = 0; |
120 | 27 | while position < buffer.len() { |
121 | 24 | let rest = &buffer[position..]; |
122 | 24 | if rest.starts_with(DSR_QUERY) { |
123 | 2 | write_to_master(master, DSR_REPLY); |
124 | 2 | position += DSR_QUERY.len(); |
125 | 2 | continue; |
126 | 22 | } |
127 | 22 | if rest.len() < DSR_QUERY.len() && DSR_QUERY13 .starts_with13 (rest13 ) { |
128 | 2 | *carry = rest.to_vec(); |
129 | 2 | break; |
130 | 20 | } |
131 | 20 | rendered.push(buffer[position]); |
132 | 20 | position += 1; |
133 | | } |
134 | 5 | return rendered; |
135 | 5 | } |
136 | | |
137 | | /// Write `bytes` to the PTY master, logging a failure. |
138 | | /// |
139 | | /// # Arguments |
140 | | /// |
141 | | /// * `master` - PTY master writer. |
142 | | /// * `bytes` - Bytes to write. |
143 | 3 | pub(crate) fn write_to_master(master: &Mutex<impl Write>, bytes: &[u8]) { |
144 | 3 | let mut writer = master.lock().unwrap_or_else(PoisonError::into_inner); |
145 | 3 | if let Err(err0 ) = writer.write_all(bytes).and_then(|()| return writer.flush()) { |
146 | 0 | error!("Failed to write to the PTY master: {}", err); |
147 | 3 | } |
148 | 3 | } |
149 | | |
150 | | #[cfg(test)] |
151 | | #[path = "../tests/client/test_pty.rs"] |
152 | | mod tests; |